package com.wangjiacai.utils.ali.ocr;

import com.alibaba.fastjson.JSONObject;
import com.wangjiacai.utils.ali.properties.AliOcrProperties;
import org.springframework.http.*;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.InputStream;
import java.util.Base64;

public class AliOcrRequest {

    private static String url="https://tysbgpu.market.alicloudapi.com/api/predict/ocr_general";

    private AliOcrProperties aliOcrProperties;
    private RestTemplate restTemplate;

    public AliOcrRequest(AliOcrProperties aliOcrProperties){
       this.aliOcrProperties=aliOcrProperties;
       this.restTemplate=new RestTemplate();
    }

    public AliOcrResponse ocrRequest(String base64String) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "APPCODE " + aliOcrProperties.getAppCode());
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        String body = "{\"image\":\""+base64String+"\"}";
        HttpEntity request=new HttpEntity(body,headers);
        ResponseEntity<String> responseEntity=restTemplate.exchange(url, HttpMethod.POST,request, String.class);
        AliOcrResponse aliOcrResponse= JSONObject.parseObject(responseEntity.getBody(),AliOcrResponse.class);
        return aliOcrResponse;
    }

    public AliOcrResponse ocrRequest(byte[] bytes) throws Exception {
        String image= Base64.getEncoder().encodeToString(bytes);
        return ocrRequest(image);
    }

    public AliOcrResponse ocrRequest(File file) throws Exception {
        return ocrRequest(FileCopyUtils.copyToByteArray(file));
    }

    public AliOcrResponse ocrRequest(InputStream inputStream) throws Exception {
        return ocrRequest(FileCopyUtils.copyToByteArray(inputStream));
    }
}
